#!/bin/bash

JAVA=$(which java)
JAVA_OPTIONS="-server -Xms2g -Xmx2g -Xmn1g -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=256m -XX:SurvivorRatio=8 -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/data/logs/$2-heapdump.hprof"
app_name=$2
jar_file="${app_name}.jar"

profiles_active="-Dspring.profiles.active=dev"
#host_ip=$(/sbin/ifconfig -a|grep inet|grep 172.16.|awk '{print $2}'|tr -d "addr:")
#config_hostIp="-Dserver.host.ip=$host_ip"

#RUOYI_ENV="$profiles_active $config_hostIp"
RUOYI_ENV="$profiles_active"

#echo "############ 应用服务启动模板 ####################"
#echo "sh springboot.sh start|stop|restart|status 服务名"
#echo "#################################################"

#echo $RUOYI_ENV
#echo $log_dir

#echo $1
#echo $2
#echo $app_name

if [ "$1" = "" ];
then
echo -e "\033[0;31m 未输入操作名 \033[0m \033[0;34m {start|stop|restart|status} \033[0m"
exit 1
fi


if [ "$2" = "" ];
then
echo -e "\033[0;31m 未输入应用名 \033[0m"
exit 1
fi


function start()
{
count=`ps -ef |grep java|grep $app_name|grep -v grep|wc -l`
if [ $count != 0 ];then
echo "$app_name is running..."
else
echo $JAVA $JAVA_OPTIONS $RUOYI_ENV -jar ${jar_file}
nohup $JAVA $JAVA_OPTIONS $RUOYI_ENV -jar ${jar_file} &>/dev/null &
#nohup $JAVA $JAVA_OPTIONS -jar ${jar_file} > ${log_file} 2>&1 &
#echo -e "Start $SpringBoot success...Please see the detail log "
fi
}


function stop()
{
echo "####################### Stop $app_name ############################"
# 下面的无限kill应用针对的是类似nginx类型的服务，针对netty类型的服务，需要时间消化通道的消息。
boot_id=`ps -ef |grep java|grep $app_name|grep -v grep|awk -F' ' '{print $2}'`
#count=`ps -ef |grep java|grep $app_name|grep -v grep|wc -l`
echo $2' pid is '$boot_id'. Now let''s kill it.'
count=3
while [ $count != 0 ];
do
kill $boot_id >> /dev/null 2>&1
count=$count-1
timeCount=1
if [ $count!=2 ]; then
#换行
echo -e '\n'
fi
while [ $timeCount != 30 ]; do
livePidCount=`ps -ef |grep java|grep $app_name|grep -v grep|wc -l`
if [ $livePidCount != 0 ];then
timeCount=$timeCount+1
sleep 2
echo -e '.\c'
else
return $? # 成功即返回
fi
done
#echo -n '.'
#boot_id=`ps -ef |grep java|grep $app_name|grep -v grep|awk '{print $app_name}'`
#kill $boot_id >> /dev/null 2>&1
done

# 如果线程还活着就kill -9
livePidCount=`ps -ef |grep java|grep $app_name|grep -v grep|wc -l`
if [ $livePidCount != 0 ]; then
kill -9 $boot_id
fi
return $?
}

function restart()
{
stop
sleep 3
start
}

function status()
{
echo "########## 查看应用服务 $app_name 是否在线 ######################"
count=`ps -ef |grep java|grep $app_name|grep -v grep|wc -l`
if [ $count != 0 ];then
echo "$app_name is running..."
else
echo "$app_name is not running..."
fi
}

case $1 in
start)
start;;
stop)
stop;;
restart)
restart;;
status)
status;;
*)

echo -e "\033[0;31m Usage: \033[0m \033[0;34m sh $0 {start|stop|restart|status} {SpringBootJarName} \033[0m
\033[0;31m Example: \033[0m
\033[0;33m sh $0 start esmart-test.jar \033[0m"
esac